//
//  YDStadusOriginalView.swift
//  YDWeibo01
//
//  Created by suibian on 16/8/13.
//  Copyright © 2016年 iitcast. All rights reserved.
//

import UIKit
import SnapKit
class YDStadusOriginalView: UIView {
//    原创微博底部约束记录
    var originalViewBottomConstraint:Constraint?
    
//
    var statusViewModel:YDStatusViewModel?{
        didSet{
            headImageView.yd_setImageWithString(statusViewModel?.statusModel?.user?.profile_image_url, placeholderImgName: "avatar_default")
            nameLable.text = statusViewModel?.statusModel?.user?.name
            timeLabel.text = dealSinaTimeStr(statusViewModel?.statusModel?.created_at ?? "")
//            微博时间
            timeLabel.text = statusViewModel?.sinaTimeStr
//            处理来源的方法  ?? 0  是int 类型赋初值 "" 是string赋初值
            
            sourceLable.text = statusViewModel?.sinaSourceStr
            rabbitView.image = statusViewModel?.verifiedImage //默认为-1 由case确定
//          微博正文
            messageLable.attributedText = statusViewModel?.orginalAttr
            HYImageView.image = statusViewModel?.mbrankImage //默认为0  否则会到拼接的图片(0-7)
            
//            卸载约束
            originalViewBottomConstraint?.uninstall()
//            判断  有配图
            if statusViewModel?.statusModel?.pic_urls?.count > 0{
//            赋值
                pictureView.pictureInfos = statusViewModel?.statusModel?.pic_urls
                self.snp_makeConstraints { (make) -> Void in
                    originalViewBottomConstraint = make.bottom.equalTo(pictureView).offset(10).constraint
                }
//             显示配图
                pictureView.hidden = false
            
            }else{  //没有配图
                self.snp_makeConstraints { (make) -> Void in
                    originalViewBottomConstraint = make.bottom.equalTo(messageLable).offset(10).constraint
                }
//             隐藏配图
                pictureView.hidden = true
            
            }
        }
        
    }
    //============================ 抽取了?
//    处理微博时间
    func dealSinaTimeStr(creatAt:String) ->String{
//        时间格式化
        let df = NSDateFormatter()
//        设置格式
        df.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
//        时间本地化
        df.locale = NSLocale(localeIdentifier: "en_US")
//        微博时间
        let sinaDate = df.dateFromString(creatAt)!
        sinaIsThisYear(sinaDate)
//        默认不是今年
        let isThisYear = sinaIsThisYear(sinaDate)
//        判断是否是今年
        if isThisYear{
        df.dateFormat = "yyyy年MM月dd日 HH:mm"
//            日历类
        let calendar = NSCalendar.currentCalendar()
//            如果是今天
            if calendar.isDateInToday(sinaDate){
//                当前时间个微博时间求差
                let s = Int(NSDate().timeIntervalSinceDate(sinaDate))
                if s < 60{
                return "刚刚"
                }else if s >= 60 && s < 3600{
                
                return "\(s/60)分钟前"
                }else{
                
                return "\(s/3600)小时前"
                
                
                }
//            是昨天
            }else if calendar.isDateInYesterday(sinaDate){
                df.dateFormat = "昨天 HH:mm"
                
//            其他
            }else{
            df.dateFormat = "MM月DD日 HH:mm"
                
            }

        }else{
        df.dateFormat = "yyyy年MM月DD日 HH:mm"
        }
            return df.stringFromDate(sinaDate)
    }
    
    func sinaIsThisYear(sinadate:NSDate) ->Bool{
        //        时间格式化
        let df = NSDateFormatter()
        //        设置格式
        df.dateFormat = "yyyy"
        //        时间本地化
        df.locale = NSLocale(localeIdentifier: "en_US")
//        微博时间字符串
        let sinaTimeStr = df.stringFromDate(sinadate)
//        当前时间
        let currentTimeStr = df.stringFromDate(NSDate())
        
    return sinaTimeStr == currentTimeStr
    }
    //============================
//    处理微博正文副文本显示 (当前是文字显示)
    func dealSinaContentAttr(text:String)->NSMutableAttributedString{
        /**
        *  正则匹配的规则
        *
        *  @param NSString 正则匹配的规则
        - 匹配的个数
        - 匹配的结果
        - 匹配的范围
        - 匹配是否停止
        *
        *  @return
        */
//        创建一个可变数组 保存拼接的模型字符串
        var matchArray:[YDMatchModel] = [YDMatchModel]()
//把当前的字符串转换为副文本
        let allTextAttr = NSMutableAttributedString(string: text)
        let regex = "\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]"
        (text as NSString).enumerateStringsMatchedByRegex(regex) { (count, result, range, _) -> Void in
//            实例化model
            let model = YDMatchModel(string:(result.memory as! String) , range: range.memory)
//            添加模型到数组中
            matchArray.append(model)
//            print(result.memory,range.memory)

            
        }
//        反向遍历数组
        for matchModel in matchArray.reverse(){
            guard let emoticonModel = YDEmoticonTools.shareTools.searchEmoticonInDefaultEmoticonsOrLxhEmoticons((matchModel.string))else{
//                防止跳出
                continue
            }
            //            创建一个文字附件
            let att = NSTextAttachment()
            //            设置行高
            let lineHight = UIFont.systemFontOfSize(15).lineHeight
            //            设置image
            att.image = UIImage.getEmoticonsImage(emoticonModel)
            att.bounds = CGRect(x: 0, y: -4, width: lineHight, height: lineHight)
            //            创建一个不可变的副文本
            let attr = NSAttributedString(attachment: att)
            //            替换
            allTextAttr.replaceCharactersInRange(matchModel.range, withAttributedString: attr)
        }
        return allTextAttr
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

//    设置视图
    private func setupUI(){
    
        
    backgroundColor = UIColor.whiteColor()
//        添加控件
//        01
        addSubview(headImageView)
//        02
        addSubview(nameLable)
//        03
        addSubview(HYImageView)
//        04
        addSubview(rabbitView)
//        05
        addSubview(timeLabel)
//        06
        addSubview(sourceLable)
//        07
        addSubview(messageLable)
//        08
        addSubview(pictureView)
        
//        添加约束
//        01
        headImageView.snp_makeConstraints { (make) -> Void in
            make.leading.top.equalTo(10)
            make.height.width.equalTo(35)
            
        }
//        02
        nameLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImageView)
            make.leading.equalTo(headImageView.snp_trailing).offset(10)
        }
//        03
        HYImageView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(nameLable)
            make.leading.equalTo(nameLable.snp_trailing).offset(10)
            
        }
//        04
        rabbitView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(headImageView.snp_bottom)
            make.centerX.equalTo(headImageView.snp_trailing)
        }
        
//        05
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(nameLable)
            make.bottom.equalTo(headImageView)
            
        }
//        06
        sourceLable.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
            make.bottom.equalTo(timeLabel)
            
        }
//        07
        messageLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headImageView.snp_bottom).offset(10)
            make.leading.equalTo(10)
            
        }
//        08
        pictureView.snp_makeConstraints { (make) -> Void in
//            约束在赋值的时候已经设置
//            make.size.equalTo(CGSize(width: 100, height: 100))
            make.top.equalTo(messageLable.snp_bottom).offset(10)
            make.leading.equalTo((KSCREENW - 250)/2)
        }
        self.snp_makeConstraints { (make) -> Void in
             originalViewBottomConstraint = make.bottom.equalTo(messageLable).offset(10).constraint
        }

    }
    
//    懒加载控件
//    01 头像
    private lazy var headImageView:UIImageView = UIImageView(imageName: "avatar_default")
//    02 名字
    private lazy var nameLable:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(15)
        
        label.textColor = UIColor.darkGrayColor()
        return label
    
    }()
//    03等级图片
    private lazy var HYImageView:UIImageView = UIImageView(imageName: "common_icon_membership")
//    04头像右下方的view
    private lazy var rabbitView:UIImageView = UIImageView(imageName: "avatar_vgirl")
//    05时间
    private lazy var timeLabel:UILabel = UILabel(textColor: AppThemeColor, textSize: 10)
//    06信息来源
    private lazy var sourceLable:UILabel = UILabel(textColor: UIColor.grayColor(), textSize: 10)
//    07主要信息
    private lazy var messageLable:UILabel = UILabel(textColor: UIColor.blackColor(), textSize: 15, maxWidth: KSCREENW - 20)
//    08配图
    private lazy var pictureView: YDStatusPictureView = YDStatusPictureView()
}
